#include "StdAfx.h"
#include "./Utility.h"


//-------------------------------------------------------------------------
// Function Name    :GetModulePath
// Parameter(s)     :HMODULE hModule	Get module handle
// Return           :The module file path
// Create			:2007-1-10 11:24	Jerry.Wang
// Memo             :Retrieve the path of the given module
//-------------------------------------------------------------------------
CString CUtility::GetModulePath(HMODULE hModule /* = NULL */)
{
	TCHAR buf[MAX_PATH] = {'\0'};
	CString strDir, strTemp;

	::GetModuleFileName( hModule, buf, MAX_PATH);
	strTemp = buf;
	strDir = strTemp.Left( strTemp.ReverseFind('\\') + 1 );
	return strDir;
}


//-------------------------------------------------------------------------
// Function Name    :IsFileExist
// Parameter(s)     :LPCTSTR lpszFilePath	File path
// Return           :
// Create			:2007-4-23 15:13	Jerry.Wang
// Memo             :verify the file exist
//-------------------------------------------------------------------------
BOOL CUtility::IsFileExist(LPCTSTR lpszFilePath)
{
	BOOL bExist = FALSE;
	HANDLE hFile = NULL;

	hFile = CreateFile( lpszFilePath
		, GENERIC_READ
		, FILE_SHARE_READ | FILE_SHARE_WRITE
		, NULL
		, OPEN_EXISTING
		, 0
		, 0
		);

	if( hFile != INVALID_HANDLE_VALUE )
	{
		CloseHandle( hFile );
		bExist = TRUE;
	}

	return bExist;
}


//-------------------------------------------------------------------------
// Function Name    :ExtractResourceToFile
// Parameter(s)     :UINT nResID			The resource id
//					:LPCTSTR lpszFilename	The file name
//					:HMODULE hModule		The module handle
// Return           :BOOL					Success on TRUE
// Create			:2007-1-8 17:35		Jerry.Wang
// Memo             :Extract resource to file
//-------------------------------------------------------------------------
BOOL CUtility::ExtractResourceToFile( LPCTSTR lpszType
									 , UINT nResID
									 , LPCTSTR lpszFilename
									 , HMODULE hModule
									 )
{
	HRSRC hRes = ::FindResource( hModule, MAKEINTRESOURCE(nResID), lpszType);
	if( hRes == NULL )
	{
		ATLASSERT(FALSE);
		return FALSE;
	}

	DWORD dwSize = ::SizeofResource( hModule, hRes); 
	if( dwSize == 0 )
	{
		ATLASSERT(FALSE);
		return FALSE;
	}

	HGLOBAL hGlobal = ::LoadResource( hModule, hRes); 
	if( hGlobal == NULL )
	{
		ATLASSERT(FALSE);
		return FALSE;
	}

	LPVOID pBuffer = ::LockResource(hGlobal); 
	if( pBuffer == NULL )
	{
		ATLASSERT(FALSE);
		::FreeResource(hGlobal); 
		return FALSE;
	}

	HANDLE hFile = ::CreateFile( lpszFilename
		, GENERIC_WRITE
		, FILE_SHARE_WRITE | FILE_SHARE_READ
		, NULL
		, CREATE_ALWAYS
		, 0
		, NULL
		);
	if( hFile == NULL )
	{
		ATLASSERT(FALSE);
		::FreeResource(hGlobal); 
		return FALSE;
	}

	DWORD dwWritten = 0;
	::WriteFile( hFile, pBuffer, dwSize, &dwWritten, NULL);
	if( dwWritten != dwSize )
	{
		ATLASSERT(FALSE);
		::FreeResource(hGlobal); 
		return FALSE;
	}

	::FlushFileBuffers(hFile);
	::CloseHandle(hFile);
	::FreeResource(hGlobal); 

	return TRUE;
}// ExtractResourceToFile


//-------------------------------------------------------------------------    
// Function Name    :LoadImage
// Parameter(s)     :UINT nID				The resource id
//					:LPCTSTR lpszType		The resource type
//					:HINSTANCE hInstance	The module handle
// Return           :Image *
// Create			:2009-3-12 14:28 Jerry.Wang                                     
// Memo             :Load the GDIPlus::Image from resource
//-------------------------------------------------------------------------   
Image * CUtility::LoadImage( UINT nID, LPCTSTR lpszType, HINSTANCE hInstance /*=NULL*/)
{
	Image * pImage = NULL;

	if( lpszType == RT_BITMAP )
	{
		HBITMAP hBitmap = ::LoadBitmap( hInstance, MAKEINTRESOURCE(nID) );
		pImage = (Image*)Bitmap::FromHBITMAP(hBitmap, 0);
		::DeleteObject(hBitmap);
		return pImage;
	}		

	hInstance = (hInstance == NULL) ? ::AfxGetResourceHandle() : hInstance;
	HRSRC hRsrc = ::FindResource ( hInstance, MAKEINTRESOURCE(nID), lpszType); 
	ASSERT(hRsrc != NULL);

	DWORD dwSize = ::SizeofResource( hInstance, hRsrc);
	LPBYTE lpRsrc = (LPBYTE)::LoadResource( hInstance, hRsrc);
	ASSERT(lpRsrc != NULL);

	HGLOBAL hMem = ::GlobalAlloc(GMEM_FIXED, dwSize);
	LPBYTE pMem = (LPBYTE)::GlobalLock(hMem);
	memcpy( pMem, lpRsrc, dwSize);
	IStream * pStream = NULL;
	::CreateStreamOnHGlobal( hMem, FALSE, &pStream);

	pImage = Image::FromStream(pStream);

	::GlobalUnlock(hMem);
	pStream->Release();
	::FreeResource(lpRsrc);

	return pImage;
}

CCriticalSection cs;
void TraceLog(char *pCFile, int iCLine, char *pFmt, ...)
{
    va_list ap;
    FILE    *fp=NULL;
    char    pFile[ 100  ];
    int iRc = 0;
	cs.Lock();
    sprintf(pFile, "log%s.txt", GetDate());
    fp=fopen(pFile, "a+");
    if ( fp == NULL)
        return;
	
    va_start(ap, pFmt);
	CString FileName = pCFile;
	CString ShortFileName = FileName.Right(FileName.GetLength() - (FileName.ReverseFind('\\') + 1));
    fprintf(fp, "[%04x] [%s] [%s:%d] " , GetCurrentThreadId(), GetTime("%02d:%02d:%02d.%03d") , ShortFileName , iCLine );
    iRc = vfprintf(fp, pFmt, ap);
    fprintf(fp, "\n");
    va_end(ap);
	
    fflush(fp);
    fclose(fp);
	cs.Unlock();
    return;
}

CString GetDate(LPTSTR fmt)
{
	CString Date;
	CTime t = CTime::GetCurrentTime();
	Date.Format(fmt, t.GetYear(), t.GetMonth(), t.GetDay());
	return Date;
}

CString GetTime(LPTSTR fmt)
{
	SYSTEMTIME sys;
	GetLocalTime(&sys);
	CString Time;
	Time.Format(fmt,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds);
	//CTime t = CTime::GetCurrentTime();
	//Time.Format(fmt, t.GetHour(), t.GetMinute(), t.GetSecond());
	return Time;
}

BOOL MStrTok(const char* src, const char *sep, int srcLen, int sepLen, CStringArray &sa) 
{ 
    if( (src == NULL) || (sep == NULL) ) 
    { 
        return FALSE; 
    } 
	
    int nMinLenSrc = min(strlen(src), (unsigned int)srcLen); 
    int nMinLensep = min(strlen(sep), (unsigned int)sepLen); 
	
    char *pNew = new char[nMinLenSrc + 1]; 
    memset(pNew, 0, nMinLenSrc + 1); 
    memcpy(pNew, src, nMinLenSrc); 
	
    char *p = (char *)pNew; 
    char c; 
	
    int i = 0, n = 0; 
    char *pStr = NULL; 
    while(*p != 0 && n < nMinLenSrc) 
    {            
        c = *sep; 
        for(i = 0; (i < nMinLensep) && (c != 0); i++) 
        { 
            c = *(sep + i); 
            if(c == *p) 
            { 
                *p = 0; 
            } 
        }    
		
        if(*p == 0) 
        { 
			//             if(pStr != NULL) 
			//             { 
			sa.Add(pStr); 
			pStr = NULL; 
			//             } 
        } 
        else  
        { 
            if (pStr == NULL)  
            { 
                pStr = p;                
            }            
        } 
		
        p++; 
        n++; 
    } 
	
    if(pStr != NULL) 
    { 
        sa.Add(pStr); 
    } 
	
    delete []pNew;   
	
    return TRUE; 
} 